package com.sqfw.project.wp.controller;

import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletResponse;

import com.sqfw.common.exception.base.BaseException;
import com.sqfw.common.utils.SecurityUtils;
import com.sqfw.framework.manager.AsyncManager;
import com.sqfw.framework.manager.factory.AsyncFactory;
import com.sqfw.project.system.domain.SysUser;
import com.sqfw.project.wp.constant.ApplyState;
import com.sqfw.project.wp.domain.DownloadApplyLog;
import com.sqfw.project.wp.domain.vo.ExportWpInfo;
import com.sqfw.project.wp.service.IWpHandleLogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.sqfw.framework.aspectj.lang.annotation.Log;
import com.sqfw.framework.aspectj.lang.enums.BusinessType;
import com.sqfw.project.wp.domain.WpApplyItem;
import com.sqfw.project.wp.service.IWpApplyItemService;
import com.sqfw.framework.web.controller.BaseController;
import com.sqfw.framework.web.domain.AjaxResult;
import com.sqfw.common.utils.poi.ExcelUtil;
import com.sqfw.framework.web.page.TableDataInfo;

/**
 * 工单申请管理Controller
 *
 * @author lx
 * @date 2023-08-14
 */
@RestController
@RequestMapping("/wp/wpApplyItem")
public class WpApplyItemController extends BaseController {
    @Autowired
    private IWpApplyItemService wpApplyItemService;

    @Autowired
    private IWpHandleLogService wpHandleLogService;


    /**
     * 查询工单申请管理列表
     * 20250611 洪磊
     */
    @PreAuthorize("@ss.hasPermi('getWpApplyItemList')")
    @GetMapping("/getWpApplyItemListNew")
    public TableDataInfo getWpApplyItemListNew(WpApplyItem wpApplyItem) {
        if (!ApplyState.LIANLUOYUAN.equals(wpApplyItem.getApplyState())){
            //查询  1审核通过 2审核中
            wpApplyItem.setStatus("1");
        }
        startPage();
        List<WpApplyItem> list = wpApplyItemService.selectWpApplyItemList(wpApplyItem);
        return getDataTable(list);
    }

    /**
     * 查询工单申请管理列表
     */
    @PreAuthorize("@ss.hasPermi('getWpApplyItemList')")
    @GetMapping("/getWpApplyItemList")
    public TableDataInfo getWpApplyItemList(WpApplyItem wpApplyItem) {
        if (!ApplyState.LIANLUOYUAN.equals(wpApplyItem.getApplyState())){
            //查询审核中
            wpApplyItem.setStatus("2");
        }
        startPage();
        List<WpApplyItem> list = wpApplyItemService.selectWpApplyItemList(wpApplyItem);
        return getDataTable(list);
    }

    @PreAuthorize("@ss.hasPermi('getWpApplyItemList')")
    @GetMapping("/getWpApplyItemListForLog")
    public TableDataInfo getWpApplyItemListForLog(WpApplyItem wpApplyItem) {
        //查询审核通过
        wpApplyItem.setStatus("1");
        startPage();
        List<WpApplyItem> list = wpApplyItemService.selectWpApplyItemList(wpApplyItem);
        return getDataTable(list);
    }

    /**
     * 热线人员查询列表
     *
     * @param wpApplyItem
     * @return
     */
    @PreAuthorize("@ss.hasPermi('getHotWpApplyItemList')")
    @GetMapping("/getHotWpApplyItemList")
    public TableDataInfo getHotWpApplyItemList(WpApplyItem wpApplyItem) {
        //热线人员只查审核通过
//        wpApplyItem.setApplyState(null); //20250610洪磊注销
        wpApplyItem.setStatus("1");
        startPage();
        List<WpApplyItem> list = wpApplyItemService.selectWpApplyItemList(wpApplyItem);
        return getDataTable(list);
    }

    /**
     * 承办单位联络员导出工单申请管理列表
     */
    @Log(title = "工单申请管理", businessType = BusinessType.EXPORT)
    @PreAuthorize("@ss.hasPermi('wpApplyItem:export')")
    @PostMapping("/export")
    public void export(HttpServletResponse response, WpApplyItem wpApplyItem) {
        WpApplyItem item = wpApplyItemService.selectWpApplyItemByAutoId(wpApplyItem.getAutoId());
        if ("临时性".equals(item.getApplyType()) && item.getDownloadCount() >= 1) {
            throw new BaseException("该申请单为临时申请，承办单位人员只能下载一次，请勿多次下载");
        }

        if (!"1".equals(item.getStatus())) {
            throw new BaseException("申请未通过，不允许下载");
        }
        item.setNextDepartment1(item.getApplyDeptId().toString());
        List<ExportWpInfo> infos = wpHandleLogService.exportWpInfos(item);
        ExcelUtil<ExportWpInfo> util = new ExcelUtil<ExportWpInfo>(ExportWpInfo.class);
        util.exportExcel(response, infos, "工单申请管理数据");

        item.setDownloadCount(item.getDownloadCount() + 1);
        wpApplyItemService.updateWpApplyItem(item);

        //记录下载日志
        this.insertDownloadApplyLog(item);

    }

    /**
     * 热线平台人员导出工单申请管理列表
     */
    @Log(title = "工单申请管理", businessType = BusinessType.EXPORT)
    @PreAuthorize("@ss.hasPermi('wpApplyItem:exportHot')")
    @PostMapping("/exportHot")
    public void exportHot(HttpServletResponse response, WpApplyItem wpApplyItem) {
        WpApplyItem item = wpApplyItemService.selectWpApplyItemByAutoId(wpApplyItem.getAutoId());
        if (!"1".equals(item.getStatus())) {
            throw new BaseException("申请未通过，不允许下载");
        }
        item.setNextDepartment1(item.getApplyDeptId().toString());
        List<ExportWpInfo> infos = wpHandleLogService.exportWpInfos(item);
        ExcelUtil<ExportWpInfo> util = new ExcelUtil<ExportWpInfo>(ExportWpInfo.class);
        util.exportExcel(response, infos, "工单申请管理数据");

        //记录下载日志
        this.insertDownloadApplyLog(item);

    }

    /**
     * 获取工单申请管理详细信息
     */
    @PreAuthorize("@ss.hasPermi('wpApplyItem:getInfo')")
    @GetMapping(value = "/{autoId}")
    public AjaxResult getInfo(@PathVariable("autoId") Long autoId) {
        return success(wpApplyItemService.selectWpApplyItemByAutoId(autoId));
    }

    /**
     * 新增工单申请管理
     */
    @Log(title = "工单申请管理", businessType = BusinessType.INSERT)
    @PreAuthorize("@ss.hasPermi('addWpApplyItem')")
    @PostMapping("/addWpApplyItem")
    public AjaxResult add(@RequestBody WpApplyItem wpApplyItem) {
        if (!"1".equals(wpApplyItem.getAgreement())) {
            return AjaxResult.error("请同意阅读隐私协议，并同意！");
        }
        WpApplyItem item = new WpApplyItem();

       List<WpApplyItem> items =  wpApplyItemService.selectWpApplyItemListByStatus(item);
       if (items.size()>0){
           return AjaxResult.error("当前部门存在审批中申请，请审批通过后再次申请！");
       }
        return toAjax(wpApplyItemService.insertWpApplyItem(wpApplyItem));
    }

    /**
     * 修改工单申请管理
     */
    @Log(title = "工单申请管理", businessType = BusinessType.UPDATE)
    @PreAuthorize("@ss.hasPermi('editWpApplyItem')")
    @PostMapping("/editWpApplyItem")
    public AjaxResult edit(@RequestBody WpApplyItem wpApplyItem) {
        return toAjax(wpApplyItemService.updateWpApplyItem(wpApplyItem));
    }

    public void insertDownloadApplyLog(WpApplyItem applyItem){
        DownloadApplyLog log = new DownloadApplyLog();
        SysUser user = SecurityUtils.getLoginUser().getUser();
        log.setApplyId(applyItem.getAutoId());
        log.setDeptId(user.getDeptId());
        log.setDownloadUser(user.getCode());
        log.setCreateBy(user.getUserName());
        log.setCreateTime(new Date());
        AsyncManager.me().execute(AsyncFactory.recordDownloadApplyLog(log));
    }


}
